package com.jielihaofeng.nio.filechannel;

import com.google.common.base.Charsets;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author Johnnie Wind
 * @description 测试 Markdown 文件读取
 * @date 2021/10/15 11:14
 */
public class MarkdownFileReader {

    public static void main(String[] args)  {
        String fileUri = "C:\\Users\\admin\\Desktop\\一台新的服务器部署dbus-wormhole.md";
//        readFile(fileUri);
//        nioReadFile(fileUri);
        fileChannelReadFile(fileUri);
    }

    public static void readFile(String fileUri) {
        try {
            StringBuffer content = new StringBuffer();
            FileInputStream fis = new FileInputStream(fileUri);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
            String line = reader.readLine();
            while (line !=null){
                content.append(line);
                content.append("\n");
                line = reader.readLine();
            }
            reader.close();
            fis.close();
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void nioReadFile(String fileUri) {
        try {
            String content = new String(Files.readAllBytes(Paths.get(fileUri)));
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void fileChannelReadFile(String fileUri) {

        try(FileChannel channel = new FileInputStream(fileUri).getChannel()) {

            StringBuffer content = new StringBuffer();

            // 定义一个 ByteBuffer，1K
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            while (channel.read(byteBuffer)>0){
                byteBuffer.flip();
                content.append(Charsets.UTF_8.decode(byteBuffer));
                byteBuffer.compact();
            }

            // 输出文件内容
            System.out.println(content.toString());

        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
